package demo.service;

import demo.Result;
import demo.entity.Salary;
import demo.entity.UserCompany;
import demo.repository.SalaryRepository;
import demo.repository.UserCompanyRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

/**
 * 薪资 Service
 *
 * @author 肖溥博文
 * @version 1.6
 */
@Service
public class SalaryService {
    @Autowired
    SalaryRepository salaryRepository;
    @Autowired
    UserCompanyRepository userCompanyRepository;

    /**
     * 设置薪资
     *
     * @param amount        金额
     * @param userCompanyId 对应工作经历 id
     * @return 结果对象，成功时返回 Salary 对象
     */
    public Result setSalary(Long amount, Long userCompanyId) {
        Salary salary = new Salary();
        salary.setUserCompanyId(userCompanyId);
        salary.setDate(new Date());
        salary.setAmount(amount);
        salaryRepository.save(salary);
        return Result.success("成功设置工资");
    }

    /**
     * 查找在职员工的当前薪资
     *
     * @param userCompanyId 工作经历 id
     * @return 结果对象，包含当前薪资的金额
     */
    public Result getSalaryByUserCompanyId(Long userCompanyId) {
        Long latestSalaryId = salaryRepository.findLatestSalaryIdByUserCompanyId(userCompanyId);
        Salary salary = salaryRepository.findSalaryById(latestSalaryId);
        if (salary == null) {
            return Result.success("不存在工资记录");
        }
        return Result.success("查找工资成功", salary.getAmount());
    }

    /**
     * 按 uid 查找所有薪资记录
     *
     * @param uid 用户 id
     * @return 结果对象，包含薪资对象的数组
     */
    public Result getSalariesByUid(Long uid) {
        List<UserCompany> userCompanyList = userCompanyRepository.findUserCompaniesByUid(uid);
        List<Salary> salaries = new ArrayList<>();

        for (UserCompany userCompany : userCompanyList) {
            salaries.addAll(salaryRepository.findAllByUserCompanyId(userCompany.getCompanyId()));
        }

        salaries.sort(Comparator.comparing(Salary::getId));
        return Result.success("历史薪资查找成功", salaries);
    }
}
